<template>
  <div class="file-bg">
    <div class="file-center">
      <el-card class="file-card">
        <div class="file-header">
          <div class="file-logo-user">
            <img src="@/assets/logo.svg" class="file-logo" />
            <span class="file-title">文件管理系统</span>
          </div>
          <div class="file-user-area">
            <span class="file-user">欢迎，用户</span>
            <el-button type="danger" size="small" circle @click="logout" class="logout-btn">
              <el-icon><SwitchButton /></el-icon>
            </el-button>
          </div>
        </div>
        <div class="file-toolbar">
          <el-upload :action="''" :http-request="customUpload" :show-file-list="false">
            <el-button type="primary" size="small" class="toolbar-btn">
              <el-icon><UploadFilled /></el-icon> 上传文件
            </el-button>
          </el-upload>
          <el-button type="success" size="small" class="toolbar-btn" @click="showCreateFolderDialog">
            <el-icon><FolderAdd /></el-icon> 新建文件夹
          </el-button>
        </div>
        <div class="file-path">
          当前位置：<span v-if="!currentPath">根目录</span><span v-else>根目录/{{ pathStack.map(p=>p.name).join('/') }}</span>
        </div>
        <el-breadcrumb separator="/" class="file-breadcrumb">
          <el-breadcrumb-item @click="goRoot" style="cursor:pointer">
            <el-icon><HomeFilled /></el-icon> 根目录
          </el-breadcrumb-item>
          <el-breadcrumb-item v-for="(p, i) in pathStack" :key="i" @click="goTo(i)" style="cursor:pointer">
            <el-icon><Folder /></el-icon> {{ p.name }}
          </el-breadcrumb-item>
        </el-breadcrumb>
        <el-table
          :data="tableDataWithBack"
          stripe
          highlight-current-row
          style="margin-top:10px"
          :header-cell-style="{background:'#f5f7fa',fontWeight:'bold'}"
          @row-click="onRowClick"
          row-class-name="tableRowClass"
        >
          <el-table-column prop="name" label="名称">
            <template #default="scope">
              <el-icon v-if="scope.row.type==='dir'" class="file-icon"><Folder /></el-icon>
              <el-icon v-else-if="scope.row.type==='file'" class="file-icon"><Document /></el-icon>
              <el-icon v-else-if="scope.row.type==='back'" class="file-icon"><Back /></el-icon>
              <span :class="{'dir-link':scope.row.type==='dir','back-link':scope.row.type==='back'}">{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型" width="80" />
          <el-table-column label="操作" width="280">
            <template #default="scope">
              <el-button-group>
                <el-button v-if="scope.row.type==='file'" @click.stop="downloadFile(scope.row)" size="small" type="success" plain class="op-btn">
                  <el-icon><Download /></el-icon> 下载
                </el-button>
                <el-button @click.stop="showMoveDialog(scope.row)" size="small" type="warning" plain class="op-btn">
                  <el-icon><Rank /></el-icon> 移动
                </el-button>
                <el-button @click.stop="confirmDelete(scope.row)" size="small" type="danger" plain class="op-btn">
                  <el-icon><Delete /></el-icon> 删除
                </el-button>
                <el-button @click.stop="shareFile(scope.row)" size="small" type="info" plain class="op-btn">
                  <el-icon><Share /></el-icon> 分享
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
        <!-- 其余弹窗和表单保持不变 -->
        <el-dialog v-model="moveDialogVisible" title="移动文件" width="400px">
          <el-form @submit.prevent="doMove">
            <el-form-item label="目标路径">
              <el-tree-select
                v-model="moveTargetPath"
                :data="allDirs"
                :load="loadNode"
                lazy
                check-strictly
                :default-expand-all="false"
                style="width:100%"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="doMove" style="border-radius: 6px;">确定</el-button>
              <el-button @click="moveDialogVisible=false" style="border-radius: 6px;">取消</el-button>
              <el-button type="success" @click="showCreateFolderDialog" style="border-radius: 6px;">新建文件夹</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
        <el-dialog v-model="createFolderDialogVisible" title="新建文件夹" width="400px" :close-on-click-modal="false">
          <el-form @submit.prevent="doCreateFolder" label-width="80px" style="padding: 10px 0;">
            <el-form-item label="父目录">
              <el-tree-select
                v-model="createFolderParent"
                :data="allDirs"
                :load="loadNode"
                lazy
                check-strictly
                :default-expand-all="false"
                style="width:100%"
                placeholder="请选择父目录"
              />
            </el-form-item>
            <el-form-item label="文件夹名">
              <el-input v-model="newFolderName" placeholder="请输入新文件夹名" clearable />
            </el-form-item>
            <el-form-item style="text-align:right;">
              <el-button type="primary" @click="doCreateFolder" style="width:100px;border-radius: 6px;">确定</el-button>
              <el-button @click="createFolderDialogVisible=false" style="margin-left:10px;width:100px;border-radius: 6px;">取消</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
        <el-dialog v-model="deleteDialogVisible" title="确认删除" width="320px">
          <div style="font-size:1.1rem;">
            确定要删除 <b>{{ deleteTarget?.name }}</b> 吗？此操作不可恢复！
            <div v-if="deleteProgress && !deleteProgress.finished" style="margin-top:12px;">
              <el-progress :percentage="Math.round((deleteProgress.progress||0)*100)" :status="deleteProgress.finished ? 'success' : 'active'" />
              <div style="font-size:0.95rem;color:#888;margin-top:4px;">{{ deleteProgress.processing_path || '' }}</div>
            </div>
          </div>
          <template #footer>
            <el-button @click="deleteDialogVisible=false" :disabled="!!deleteTaskId">取消</el-button>
            <el-button type="danger" @click="doDelete" :disabled="!!deleteTaskId">删除</el-button>
          </template>
        </el-dialog>
        <el-dialog v-model="shareDialogVisible" title="分享链接" width="480px" :close-on-click-modal="false">
          <el-input v-model="shareLink" readonly style="margin-bottom: 16px;" />
          <el-button type="primary" @click="copyShareLink" style="width: 100%;">一键复制</el-button>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { getShares, getFiles, uploadFile, moveFile, getDownloadUrl, createFolder, deleteFile, deleteStatus, qunhuiDirectUpload, createShare } from '../api'
import { ElMessage } from 'element-plus'
import { ElDialog, ElInput, ElButton } from 'element-plus'
import { UploadFilled, FolderAdd, HomeFilled, Folder, Document, Back, Download, Rank, Delete, Share, SwitchButton } from '@element-plus/icons-vue'

const props = defineProps({ sid: String })
const displayList = ref([])
const pathStack = ref([]) // [{name, path}]
const currentPath = ref('')

// 表格数据，非根目录时首行加“返回上一级”
const tableDataWithBack = computed(() => {
  if (!currentPath.value) return displayList.value
  return [
    { name: '返回上一级', type: 'back', path: null },
    ...displayList.value
  ]
})

// 懒加载目录树
const allDirs = ref([])
const fetchRootDirs = async () => {
  const res = await getShares(props.sid)
  const shares = res.data.shares || []
  allDirs.value = shares.map(share => ({
    label: share.name,
    value: share.path,
    isLeaf: false
  }))
}
const loadNode = async (node, resolve) => {
  if (node.level === 0) {
    resolve(allDirs.value)
    return
  }
  const path = node.data.value
  const res = await getFiles(props.sid, path)
  const subDirs = (res.data.files || []).filter(f => f.isdir)
  resolve(subDirs.map(f => ({
    label: f.name,
    value: f.path,
    isLeaf: false
  })))
}

// 移动相关
const moveDialogVisible = ref(false)
const moveTargetPath = ref('')
const moveSrc = ref(null)

const showMoveDialog = async (row) => {
  moveSrc.value = row.path
  moveTargetPath.value = ''
  moveDialogVisible.value = true
  await fetchRootDirs()
}
const doMove = async () => {
  if (!moveTargetPath.value) {
    ElMessage.error('请选择目标路径')
    return
  }
  try {
    const res = await moveFile(props.sid, moveSrc.value, moveTargetPath.value)
    if (res.success === false) {
      ElMessage.error('移动失败: ' + (res.error?.code || '未知错误'))
      return
    }
    ElMessage.success('移动成功')
    moveDialogVisible.value = false
    if (currentPath.value) openFolder({ path: currentPath.value, name: '' })
    else loadShares()
  } catch {
    ElMessage.error('移动失败')
  }
}

// 新建文件夹相关
const createFolderDialogVisible = ref(false)
const newFolderName = ref('')
const createFolderParent = ref('')

const showCreateFolderDialog = async () => {
  createFolderDialogVisible.value = true
  newFolderName.value = ''
  await fetchRootDirs()
  createFolderParent.value = currentPath.value || (allDirs.value[0] && allDirs.value[0].value) // 默认当前目录或根目录
}
const doCreateFolder = async () => {
  if (!createFolderParent.value) {
    ElMessage.error('请选择父目录')
    return
  }
  if (!newFolderName.value) {
    ElMessage.error('请输入文件夹名')
    return
  }
  try {
    const res = await createFolder(props.sid, createFolderParent.value, newFolderName.value)
    if (res.success === false) {
      ElMessage.error('新建失败: ' + (res.error?.code || '未知错误'))
      return
    }
    ElMessage.success('新建成功')
    createFolderDialogVisible.value = false
    await fetchRootDirs()
    // 如果新建在当前目录，刷新文件列表
    if (createFolderParent.value === currentPath.value) {
      if (currentPath.value) openFolder({ path: currentPath.value, name: '' })
      else loadShares()
    }
  } catch {
    ElMessage.error('新建失败')
  }
}

// 下载
const downloadFile = (row) => {
  const url = getDownloadUrl(props.sid, row.path)
  window.open(url, '_blank')
}

// 删除相关
const deleteDialogVisible = ref(false)
const deleteTarget = ref(null)
const deleteProgress = ref(null)
const deleteTaskId = ref(null)
const deletePolling = ref(null)
const confirmDelete = (row) => {
  deleteTarget.value = row
  deleteDialogVisible.value = true
  deleteProgress.value = null
  deleteTaskId.value = null
}
const doDelete = async () => {
  if (!deleteTarget.value) return
  try {
    const res = await deleteFile(props.sid, deleteTarget.value.path)
    if (res.success === false) {
      ElMessage.error('删除失败: ' + (res.error?.code || '未知错误'))
      return
    }
    if (res.data && res.data.taskid) {
      // 非阻塞删除，轮询进度
      deleteTaskId.value = res.data.taskid
      pollDeleteStatus()
    } else {
      // 小文件/空文件夹可能直接完成
      ElMessage.success('删除成功')
      deleteDialogVisible.value = false
      if (currentPath.value) openFolder({ path: currentPath.value, name: '' })
      else loadShares()
    }
  } catch {
    ElMessage.error('删除失败')
  }
}
const pollDeleteStatus = async () => {
  if (!deleteTaskId.value) return
  try {
    const res = await deleteStatus(props.sid, deleteTaskId.value)
    if (res.data) {
      deleteProgress.value = res.data
      if (res.data.finished) {
        ElMessage.success('删除成功')
        deleteDialogVisible.value = false
        deleteTaskId.value = null
        if (currentPath.value) openFolder({ path: currentPath.value, name: '' })
        else loadShares()
        return
      }
    }
  } catch {}
  deletePolling.value = setTimeout(pollDeleteStatus, 1000)
}
watch(deleteDialogVisible, (val) => {
  if (!val && deletePolling.value) {
    clearTimeout(deletePolling.value)
    deletePolling.value = null
    deleteProgress.value = null
    deleteTaskId.value = null
  }
})

// 加载根目录（共享文件夹）
const loadShares = async () => {
  const res = await getShares(props.sid)
  displayList.value = (res.data.shares || []).map(s => ({
    name: s.name,
    path: s.path,
    type: 'dir'
  }))
  pathStack.value = []
  currentPath.value = ''
}

// 进入文件夹
const openFolder = async (row, isBack = false) => {
  const res = await getFiles(props.sid, row.path)
  displayList.value = (res.data.files || []).map(f => ({
    name: f.name,
    path: f.path,
    type: f.isdir ? 'dir' : 'file'
  }))
  if (!isBack) {
    pathStack.value.push({ name: row.name, path: row.path })
  }
  currentPath.value = row.path
}

// 返回根目录
const goRoot = () => loadShares()

// 跳转到某一级
const goTo = async (idx) => {
  if (idx < 0) return loadShares()
  const p = pathStack.value[idx]
  pathStack.value = pathStack.value.slice(0, idx + 1)
  await openFolder(p, true)
}

// 上传文件
const customUpload = async ({ file }) => {
  // 直连群晖上传，sid 使用前端保存的 props.sid，path 用用户当前选择的目录
  const sid = props.sid;
  const path = currentPath.value || '/'; // 如果没选目录则为根目录
  const filename = file.name; // 使用文件原名
  try {
    const res = await qunhuiDirectUpload(sid, path, file, filename);
    // 先打印返回体
    console.log('上传返回体:', res);
    // 无论返回内容如何，都提示上传已发起
    ElMessage.success('上传已发起（请在群晖后台确认）')
    if (currentPath.value) openFolder({ path: currentPath.value, name: '' })
    else loadShares()
  } catch (err) {
    // 只要发起了请求就算上传成功，忽略跨域报错
    if (err && err.response) {
      console.log('上传异常返回体:', err.response.data);
    } else {
      console.log('上传异常:', err);
    }
    ElMessage.success('上传已发起（请在群晖后台确认）')
    if (currentPath.value) openFolder({ path: currentPath.value, name: '' })
    else loadShares()
  }
}

// 分享文件
const shareDialogVisible = ref(false)
const shareLink = ref('')

const shareFile = async (row) => {
  try {
    const res = await createShare(props.sid, row.path, row.name, '当前用户', null)
    const shareUrl = res.url + '?sid=' + encodeURIComponent(props.sid)
    shareLink.value = shareUrl
    shareDialogVisible.value = true
    ElMessage.success('分享链接已生成')
  } catch (e) {
    ElMessage.error('生成分享链接失败')
  }
}

const copyShareLink = async () => {
  try {
    await navigator.clipboard.writeText(shareLink.value)
    ElMessage.success('已复制到剪贴板')
  } catch {
    ElMessage.error('复制失败，请手动复制')
  }
}

// 表格行点击事件
const onRowClick = (row) => {
  if (row.type === 'dir') {
    openFolder(row)
  } else if (row.type === 'back') {
    goBack()
  }
}
const goBack = () => {
  if (pathStack.value.length === 0) return
  pathStack.value.pop()
  const prev = pathStack.value[pathStack.value.length - 1]
  if (prev) {
    openFolder(prev, true)
  } else {
    loadShares()
  }
}

const logout = () => {
  window.location.reload()
}

onMounted(loadShares)
</script>

<style scoped>
.file-bg {
  min-height: 100vh;
  background: linear-gradient(135deg, #f0fdfa 0%, #e0e7ff 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
}
.file-center {
  width: 100vw;
  max-width: 1200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.file-card {
  width: 100%;
  max-width: 1100px;
  margin: 0 auto;
  padding: 36px 40px 40px 40px;
  box-shadow: 0 8px 32px rgba(0,0,0,0.10);
  border-radius: 22px;
  background: rgba(255,255,255,0.98);
  transition: padding 0.2s, max-width 0.2s;
}
.file-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  gap: 12px;
}
.file-logo-user {
  display: flex;
  align-items: center;
  gap: 12px;
}
.file-logo {
  width: 38px;
  height: 38px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}
.file-user-area {
  display: flex;
  align-items: center;
  gap: 8px;
}
.file-user {
  font-size: 1.08rem;
  color: #666;
  margin-right: 4px;
}
.logout-btn {
  background: #fff0f0;
  border-radius: 50%;
  box-shadow: 0 2px 8px rgba(255,0,0,0.08);
}
.file-toolbar {
  display: flex;
  gap: 12px;
  margin-bottom: 10px;
}
.toolbar-btn {
  border-radius: 8px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(64,158,255,0.08);
  transition: box-shadow 0.2s, transform 0.2s;
}
.toolbar-btn:hover {
  box-shadow: 0 4px 16px rgba(64,158,255,0.18);
  transform: translateY(-2px) scale(1.04);
}
.file-path {
  margin-bottom: 10px;
  font-weight: bold;
  font-size: 1.08rem;
}
.file-icon {
  margin-right: 6px;
  vertical-align: middle;
}
.op-btn {
  border-radius: 8px;
  margin-right: 4px;
  font-weight: 500;
}
.el-button-group .el-button:not(:last-child) {
  margin-right: 0;
}
.file-title {
  font-size: 2rem;
  font-weight: bold;
  color: #409eff;
  letter-spacing: 2px;
}
.file-breadcrumb {
  margin-bottom: 16px;
}
.el-table {
  font-size: 1.08rem;
}
.el-table th, .el-table td {
  padding: 14px 8px;
}
.el-button {
  font-size: 1rem;
}
.dir-link {
  color: #409eff;
  cursor: pointer;
  font-weight: bold;
  transition: text-decoration 0.2s;
}
.dir-link:hover {
  text-decoration: underline;
}
.back-link {
  color: #67c23a;
  cursor: pointer;
  font-weight: bold;
}
.el-table__row.back-row {
  background: #f6fff6 !important;
}
/* 响应式优化 */
@media (max-width: 1200px) {
  .file-center, .file-card {
    max-width: 98vw;
    padding-left: 8px;
    padding-right: 8px;
  }
}
@media (max-width: 900px) {
  .file-card {
    padding: 12px 2vw 12px 2vw;
    max-width: 99vw;
  }
  .file-title {
    font-size: 1.1rem;
  }
  .el-table th, .el-table td {
    padding: 10px 4px;
  }
}
@media (max-width: 600px) {
  .file-card {
    padding: 4px 1vw 8px 1vw;
    border-radius: 10px;
  }
  .file-title {
    font-size: 1rem;
  }
  .file-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
  }
  .el-table {
    font-size: 0.95rem;
  }
  .file-toolbar {
    flex-direction: column;
    gap: 6px;
  }
}
</style> 